<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Models\NewsType;
use App\Models\WeixinUser;
use App\Repositories\TakeoutRepository;
use App\User;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Transfer;
use function GuzzleHttp\Psr7\build_query;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;
use EasyWeChat\Kernel\Messages\News;
use EasyWeChat\Kernel\Messages\NewsItem;
//use Session;
class WechatController extends Controller
{

    /**
     * 处理微信的请求消息
     *
     * @return string
     */
    public function serve()
    {

        Log::info('request arrived.');
        $app = app('wechat.official_account');
        $app->server->push(function ($message) {
            $zlt_msg = "欢迎关注掌里通智慧餐饮系统 
亲，发暗号给我~
我会给你想要的！！
我们的暗号有：
    外卖
    预定
    排队
    最新优惠
    电话
试试发 客服 ，有客服萌萌哒~
试试看吧~";
            Log::info('---------------------------------yes----------------------------------------------');
            Log::info($message);
            Log::info('-----------------------------------yes--------------------------------------------');
            switch ($message['MsgType']) {
                case 'event':
                    if($message['Event'] == 'subscribe'){
                        $subscribe = config('Text')['subscribe'];
                        foreach ($subscribe as $sub){
                            $is = new NewsItem([
                                'title'       => $sub['title'],
                                'description' => $sub['description'],
                                'url'         =>$sub['url'],
                                'image'       => $sub['image'],
                            ]);
                            $items[] = $is;
                        }
                        $news = new News($items);
                        return $news;
                    }
//                    return $zlt_msg.'收到事件消息';
//                    return 'hello event';
                    break;
                case 'text':
                    $customer_service = ['客服','人工','人工客服','咨询'];
                    if (in_array($message['Content'],$customer_service)){
                        $app = app('wechat.official_account');
                        $online = $app->customer_service->online();
                        if (count($online['kf_online_list'])>0){
                           return new Transfer();
                        }else{
                            return "当前服务人数较多，请稍后再试";
                        }
                        break;//zlt.1.0.apk
                    }else if ($message['Content'] == '电话'){
                        return "掌里通唯一官方电话：020-36910000(转8)";
                        break;
                    }else if($message['Content'] == '图文'){
                        $items = [
                            new NewsItem([
                                'title'       => "“高铁霸座事件”的主角，如果不是被人肉你会主动出来道歉？",
                                'description' => '“高铁霸座事件”的主角，如果不是被人肉你会主动出来道歉？',
                                'url'         => env("APP_URL"),
                                'image'       => env("APP_URL").'/img/eat.png',
                            ]),
                            new NewsItem([
                                'title'       => "“高铁霸座事件”的主角，如果不是被人肉你会主动出来道歉？",
                                'description' => '“高铁霸座事件”的主角，如果不是被人肉你会主动出来道歉？',
                                'url'         => env("APP_URL"),
                                'image'       => env("APP_URL").'/img/eat.png',
                            ]),
                            new NewsItem([
                                'title'       => "“高铁霸座事件”的主角，如果不是被人肉你会主动出来道歉？",
                                'description' => '“高铁霸座事件”的主角，如果不是被人肉你会主动出来道歉？',
                                'url'         => env("APP_URL"),
                                'image'       => env("APP_URL").'/img/eat.png',
                            ])
                        ];
                        $news = new News($items);
                        return $news;
                        break;
                    }else{
                        return $zlt_msg;
                        break;
                    }
                    break;
                case 'image':   // 收到图片消息
                    return $zlt_msg;
                    break;
                case 'voice':   // 收到声音消息
                    return $zlt_msg;
                    break;
                case 'video':   //收到视频消息
                    return $zlt_msg;
                    break;
                case 'location':    //收到坐标消息
                    return $zlt_msg;
                    break;
                case 'link':    //收到链接消息
                    return $zlt_msg;
                    break;
                case 'file':       // 收到文件消息
                    return $zlt_msg;
                // ... 其它消息
                default:        // 收到其它消息
                    return $zlt_msg;
                    break;
            }
        });
        return $app->server->serve();
    }
    public function login(){
        $user = session('wechat.oauth_user'); // 拿到授权用户资料
        $user_info = $user['default']['original'];
        $user_info['privilege'] = '';
        try{
            // @todo 真实使用时用 unionid 判断
            $res = WeixinUser::where('openid',$user_info['openid'])->first();
            if ($res){
                // 如何与现有的登陆合作       手机号
                if ($res->user_id != '0'){
                    $user = User::where('id',$res->user_id)->first();
                    Auth::login($user);
                    return redirect()->back();
                }else{
                    return show(202,'请绑定手机号');
                }

            }else{
                // 如何直接登陆
                // 开始注册
                WeixinUser::create($user_info);
                return show(202,'请绑定手机号');
            }
        }catch(\Exception $e){
            return show(201,'微信登陆失败，请重试');
        }
    }
    // 发送验证码
    public function send(Request $request){
        if(preg_match("/^1[345678]{1}\d{9}$/",$request->mobile)){
            //生成验证码存入缓存
            $code = rand(100000,999999);
            Cache::put('gzh'.$request->mobile, ['mobile'=>$request->mobile,'code'=>$code], 60);

            //发送短信
            $url="http://send.18sms.com/msg/HttpBatchSendSM?account=vd736g&pswd=dTP8X306&mobile=".$request->mobile."&msg=%E6%82%A8%E7%9A%84%E9%AA%8C%E8%AF%81%E7%A0%81%E6%98%AF%EF%BC%9A".$code."&needstatus=true&extno=";
            file_get_contents($url);
            return show(200,'发送成功');
        }else{
            return show(201,'发送失败，请重试');

        }
    }
    // 验证当前用户 微信公众号
    public function checkUser(Request $request){
        $code =$request->code;
        $mobile = $request->mobile;
//        $token = $request->token;
        $ilike =  Cache::get('gzh'.$mobile);
        $sessionMobile = $ilike['mobile'];
        $sessionValidateCode =  $ilike['code'];

        if (!isset($code) || !isset($mobile) ){//|| !isset($token) || strlen($token)<6){
            return show(201,'请传手机号或验证码');
        }

        if(($mobile != $sessionMobile) || ($code != $sessionValidateCode)){
            return show(201,'请传手机号或验证码');
        }
        //验证用户是否存在
        $user = User::where('mobile',$request->mobile)->first();
        $wechat_user = session('wechat.oauth_user'); // 拿到授权用户资料
        $user_info = $wechat_user['default']['original'];
        $open_id = $user_info['openid'];
        try{
            if($user){
                $user_id = $user->id;
                WeixinUser::where('openid',$open_id)->update(compact('user_id'));
            }else{
                $res = User::create([
                    'name'=> $mobile,
                    'mobile'=>$mobile,
                    'password'=>Hash::make($code),
                ]);
                $user_id = $res->id;
                WeixinUser::where('openid',$open_id)->update(compact('user_id'));
            }
        }catch (\Exception $e){
//            dd($e->getMessage());
            return show(202,'绑定失败,请重试或联系客服');
        }
        return show(200,'绑定成功');
    }


    // 自定义菜单
    public function menu(Request $request){
        if (!isset($request->testmsg)){
            return;
        }
        if (isset($request->testmsg) && $request->testmsg == 'zhanglitong321'){
            Log::info('---------------------------------------  menu start ---------------------------------------------------------------');
            $app = app('wechat.official_account');
            $list = $app->menu->list();
//        dd($list);
            $buttons = [
                [
                    "type" => "click",
                    "name" => "今日歌曲",
                    "key"  => "V1001_TODAY_MUSIC"
                ],
                [
                    "name"       => "菜单",
                    "sub_button" => [
                        [
                            "type" => "view",
                            "name" => "搜索",
                            "url"  => "http://www.soso.com/"
                        ],
                        [
                            "type" => "view",
                            "name" => "首页",
                            "url"  => env('APP_URL').'/mobile'
                        ],
                        [
                            "type" => "click",
                            "name" => "赞一下我们",
                            "key" => "V1001_GOOD"
                        ],
                    ],
                ],
            ];
            $res = $app->menu->create($buttons);
            dd($res);
        }else{
            return;
        }

    }
    // 客服消息
    public function customer(Request $request){
        $app = app('wechat.official_account');
        $list = $app->customer_service->list();
        $online = $app->customer_service->online();
//       var_dump(count($online['kf_online_list']));die;
        return [$list,$online];
    }
    // 发送模板消息
    public function sendTemplate($openid = 'ovIs0wi6SppFsOQsa9PVg_iYAqlg'){
        $openid = 'ovIs0wi6SppFsOQsa9PVg_iYAqlg';
        $app = app('wechat.official_account');
        $res = $app->template_message->send([
            'touser' => $openid,
            'template_id' => 'XnGCIOztROl_Qoxf8BzowRFSuSjl9wYnqxjmL6nY_Bw',
            'url' => env('APP_URL').'/mobile',
            'data' => [
                'act' => '恭喜您成功购买',
                'name' => ''.randID(),
                'money' => '1000元',
                'date'=>date("Y-m-d H:i:s")
            ],
        ]);
        Log::info($res);
    }
    // 关注公众号的用户列表,后期屏蔽，不给public调用
    public function userlist(){
        $app = app('wechat.official_account');
        $list = $app->user->list($nextOpenId = null);  // $nextOpenId 可选
        $user_list = $list['data']['openid'];
        foreach ($user_list as $user){
            $users[] = $app->user->get($user);
        }
        return show(200,'微信公众号用户列表',$users);

    }
    // excel 下载demo
    public function exceldemo(){

        $cellData = [
            ['id','姓名','年龄'],
            ['10001','张三','19'],
            ['10002','李四','22'],
            ['10003','王五','23'],
            ['10004','赵六','19'],
            ['10005','猴七','22'],
        ];
        try{
            $name = iconv('UTF-8', 'GBK', 'test');
            Excel::create($name,function($excel) use ($cellData){
                $excel->sheet('user', function($sheet) use ($cellData){
                    $sheet->rows($cellData);
                });

            })->store('xls')->export('xls');
        }catch (\Exception $e){
            dd($e->getMessage());
        }
    }
    // 获取 access_token
    public function getToken(){
        $app = app('wechat.official_account');
        $accessToken = $app->access_token;
//        $token = $accessToken->getToken(); // token 数组  token['access_token'] 字符串
        $token = $accessToken->getToken(true); // 强制重新从微信服务器获取 token.
        dd($token);
    }

    // 获取某个用户的信息
    //  unionid	只有在用户将公众号绑定到微信开放平台帐号后，才会出现该字段。
    public function info(){
        $app = app('wechat.official_account');
        $openid = 'ovIs0wi6SppFsOQsa9PVg_iYAqlg';
        $user = $app->user->get($openid);
        dd($user);
    }


    // 发送短信
    public function sendSms(Request $request){
        if(preg_match("/^1[345678]{1}\d{9}$/",$request->mobile)){
            //生成验证码存入缓存
            $code = rand(100000,999999);
            Cache::put($request->mobile, ['mobile'=>$request->mobile,'code'=>$code], 60);

            //发送短信 2900+1200-628-1300
            $url="http://send.18sms.com/msg/HttpBatchSendSM?account=vd736g&pswd=dTP8X306&mobile=".$request->mobile."&msg=%E6%82%A8%E7%9A%84%E9%AA%8C%E8%AF%81%E7%A0%81%E6%98%AF%EF%BC%9A".$code."&needstatus=true&extno=";
            file_get_contents($url);
            return ["code"=>200,"info"=>"发送成功","data"=>[]];
        }else{
            return ["code"=>201,"info"=>"手机号错误","data"=>[]];

        }
    }
    public function createCard(){
        $app = app('wechat.official_account');
        $cardType = 'GROUPON';

        $attributes = [
            'base_info' => [
                'brand_name' => '微信餐厅',
                'code_type' => 'CODE_TYPE_TEXT',
                'title' => '132元双人火锅套餐',
                //...
            ],
            'advanced_info' => [
                'use_condition' => [
                    'accept_category' => '鞋类',
                    'reject_category' => '阿迪达斯',
                    'can_use_with_other_discount' => true,
                ],
                //...
            ],
        ];
        $card = $app->card;
        $result = $card->create($cardType, $attributes);
        dd($result);
    }
    public function createCardLogo(Request $request){
        $app = app('wechat.official_account');
        $accessToken = $app->access_token;
        $token = $accessToken->getToken();

        $url = 'https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token='.$token['access_token'];
        $buffer = env("APP_URL")."/img/aq.png";
        $res = doCurl($url,1,[
            'media'=>$buffer,
            'access_token'=>$token['access_token']
        ]);
        dd($res);
    }
    public function uploadCard(){
        try{
            $app = app('wechat.official_account');
            $accessToken = $app->access_token;
            $token = $accessToken->getToken();
////        dd($token['access_token']);
            $url = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token={$token['access_token']}";
//            $logo ='D:\zhanglitong\public\img\aq.png'; // 一定要图片的绝对路径
//            $file = new \CURLFile(realpath($logo));   // php5.6以后用到这个curlfile类
//            $arr['buffer'] = $file;           // 文件的数据流
//            $arr['access_token'] = $token;   // 调用接口凭证
//
//            $output = doCurl($url,1,$arr);
//            dd(json_encode($output,true));
            $data = array('buffer' => '/var/www_new/zhanglitong/public/img/aq.png');
            $curl=curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
            if(!empty($data)){
                curl_setopt($curl, CURLOPT_POST, 1);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
            curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);
//            curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Content-Length: ' . strlen($data)));
            $result=curl_exec($curl);
            var_dump($result);exit;
//            curl_close($curl);
//            $result = json_decode($result, true);
//            return $result;

        }catch (\Exception $e){
            dd($e->getMessage());
        }
    }

    // 表情包处理
    public function emoji($emoji_str)

    {

//将字符串组合成json格式

        $emoji_str = '["'.$emoji_str.'"]';

        $emoji_arr = json_decode($emoji_str, true);

        if (count($emoji_arr) == 1){
            return $emoji_arr[0];
        }else{
            return "";
        }


    }
}
